import request from '@/utils/api'

export const login = (credentials) => 
  request.post('/api/users/login', credentials)
    .then(res => res) 
       .catch(error => ({
         code: error.response?.status || 500,
         msg: error.response?.data?.msg || error.message,
         data: null
       }))
	   
export const register = (credentials) => 
  request.post('/api/users/register', credentials)
    .then(res => res)
        .catch(error => ({
          code: error.response?.status || 500,
          msg: error.response?.data?.msg || error.message,
          data: null
        }))

export const logout = () => 
  request.post('/api/users/logout', null, {
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    }
  })
  .then(res => {
    const backendResponse = res.data
    return {
      code: backendResponse.code || 200,
      msg: backendResponse.msg || '登出成功',
      data: backendResponse.data || null
    }
  })
  .catch(error => ({
    code: 200,
    msg: '登出成功',
    data: null
  }))

export const getCurrentUser = (id) => {
  if (!id) return Promise.reject(new Error('缺少用户ID'))
  
  return request.get(`/api/users/${id}`)
    .then(res => {
      const backendResponse = res.data
      if (backendResponse.code !== 200) {
        throw new Error(backendResponse.msg || '无效响应数据')
      }
      
      const userData = backendResponse.data?.user || backendResponse.data
      if (!userData) throw new Error('未找到用户信息')
      
      // 适配后端返回的用户数据结构
      return {
        id: userData.id,
        username: userData.username,
        nickname: userData.nickname,
        email: userData.email,
        avatarUrl: userData.avatarUrl,
        bio: userData.bio,
        followingCount: userData.followingCount || 0,
        followersCount: userData.followersCount || 0,
        notesCount: userData.notesCount || 0,
        createdAt: userData.createdAt,
        updatedAt: userData.updatedAt
      }
    })
    .catch(error => {
      if (error.response?.status === 404) throw new Error('用户不存在')
      throw error
    })
}

export const updateUser = async (id, data) => {
  try {
    const res = await request.put(`/api/users/${id}`, data) // 此时 res = {code:200,msg:"...",data:...}

    // 1. 如果后端返回的就是包装对象，直接用它
    if (res && typeof res === 'object' && 'code' in res) {
      return {
        code: res.code,
        msg:  res.msg ?? '更新成功',
        data: res.data ?? null
      }
    }

    // 2. 极端情况：后端只返回纯数据，手动包
    return {
      code: 200,
      msg: '更新成功',
      data: res ?? null
    }
  } catch (error) {
    return {
      code: error.response?.status || 500,
      msg:  error.response?.data?.msg || error.message || '服务器异常',
      data: null
    }
  }
}

export const updatePwd = async (id, { oldPassword, newPassword }) => {
  try {
    const res = await request.patch(`/api/users/${id}/password`, { oldPassword, newPassword })

    if (res && typeof res === 'object' && 'code' in res) {
      return {
        code: res.code,
        msg: res.msg || '密码更新成功',
        data: res.data ?? null
      }
    }

    return {
      code: 200,
      msg: '密码更新成功',
      data: res ?? null
    }
  } catch (error) {
    return {
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message || '服务器异常',
      data: null
    }
  }
}

export const checkUsername = (username) => 
  request.get('/api/users/check-username', { params: { username } })
    .then(res => {
      const backendResponse = res.data
      return {
        code: backendResponse.code || 200,
        msg: backendResponse.msg || '操作成功',
        data: backendResponse.data || null
      }
    })
    .catch(error => ({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message,
      data: null
    }))

export const checkEmail = (email) => 
  request.get('/api/users/check-email', { params: { email } })
    .then(res => {
      const backendResponse = res.data
      return {
        code: backendResponse.code || 200,
        msg: backendResponse.msg || '操作成功',
        data: backendResponse.data || null
      }
    })
    .catch(error => ({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message,
      data: null
    }))

export const updateUserInfo = updateUser
export const updatePassword = updatePwd